﻿using Ingr.SP3D.Common.Middle.Services;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SWS.PIP.DM
{
	public class SQLDBConnectionHelper
	{
		static string m_sConnectionString = "";
		static SqlConnection conn = null;

		public static SqlConnection GetSqlConnection()
		{
			if (conn == null)
				conn = new SqlConnection(GetConnnectionString());

			if (conn.State != System.Data.ConnectionState.Open)
				conn.Open();

			return conn;
		}

		public static string GetConnnectionString()
		{
			if (m_sConnectionString == "")
			{
				string strPath = MiddleServiceProvider.SiteMgr.ActiveSite.ActivePlant.PlantCatalog.SymbolShare + "\\CustomerDef\\" + Assembly.GetExecutingAssembly().GetName().Name + ".dll.config";
				ExeConfigurationFileMap map = new ExeConfigurationFileMap();
				map.ExeConfigFilename = strPath;

				Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

				try
				{
					m_sConnectionString = configuration.ConnectionStrings.ConnectionStrings["SqlServer"].ConnectionString;
					if (!m_sConnectionString.Contains("Initial Catalog"))
					{
						string sModelName = MiddleServiceProvider.SiteMgr.ActiveSite.ActivePlant.Name;
						m_sConnectionString += ";Initial Catalog=" + sModelName;
					}
				}
				catch (Exception ex)
				{
					throw new Exception($"请检查配置文件{strPath}及配置项SqlServer是否配置正确。");
				}
				
			}

			return m_sConnectionString;
		}
	}
}
